<?php
declare (strict_types = 1);

namespace app\middleware;

use app\common\exception\LogicException;
use app\model\UserToken;

/**
 * 检查用户是否已经登录
 */
class CheckUserLogin
{
    /**
     * @Description 处理请求
     * @author: zj
     * @param $request
     * @param \Closure $next
     * @time 2024/03/18 18:10:42
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($request, \Closure $next)
    {
        //判断是否传token
        $token = $request->header('token');
        if (!$token) {
            throw new LogicException('登录已过期，请重新登录', 4101);
        }
        $userTokenModel = new UserToken();
        $userTokenModel->checkUserToken($token);

        //判断token是否过期
        $tokenData = Cache()->get('user_'.$token);
        if (!$tokenData) {
            throw new LogicException('登录已过期，请重新登录', 4101);
        }

        //更新token过期时间
        Cache()->set('user_'.$token, $tokenData, 86400);

        $tokenData = json_decode($tokenData, true);
        $request->user_info = $tokenData;
        
        return $next($request);
    }
}
